﻿// This code is released under the BSD license.
namespace PugLib.Filters
{
    using System;
    using System.Linq.Expressions;
    using Conditions;

    public static class FunctionFactory
    {
        public static Func<T, bool> MakeFunction<T>(T obj, SearchFilter filter)
        {
            Filter mappedFilter = MapFilter(filter.SearchOperator);
            Condition<T, string> condition = Condition.Create(obj, filter.Field, mappedFilter, filter.SearchText);
            return condition.MakeFunc();
        }

        public static LambdaExpression MakeExpression<T>(T obj, SearchFilter filter)
        {
            Filter mappedFilter = MapFilter(filter.SearchOperator);
            Condition<T, string> condition = Condition.Create(obj, filter.Field, mappedFilter, filter.SearchText);
            return condition.MakeExpression();
        }


        private static Filter MapFilter(SearchOperator searchOperator)
        {
            switch (searchOperator)
            {
                case SearchOperator.Contains:
                    return Filter.Contains;
                case SearchOperator.DoesNotContain:
                    return Filter.DoesNotContain;
                case SearchOperator.StartsWith:
                    return Filter.StartsWith;
                case SearchOperator.EndsWith:
                    return Filter.EndsWith;
                case SearchOperator.Is:
                    return Filter.Is;
                case SearchOperator.IsNot:
                    return Filter.IsNot;
                case SearchOperator.WithinThePastDays:
                    return Filter.WithinThePastDays;

                case SearchOperator.IsAfter:
                case SearchOperator.IsGreaterThan:
                    return Filter.GreaterThan;

                case SearchOperator.IsBefore:
                case SearchOperator.IsLessThan:
                    return Filter.LessThan;
                default:
                    throw new ArgumentException("unmapped SearchOperator");
            }
        }
    }
}